<?php
namespace app\common\model;

use think\Request;

class AdminUser extends Common {
	protected $insert = ['addtime' => SYS_TIME, 'avatar', 'initial', 'register_code'];
	protected $pk = 'userid';
	// 追加属性
	protected $append = [
		'zjname',
		'store_name',
		'identity_name',
		'avatar',
		'vipenddate',
	];
	protected static function init() {
		self::beforeInsert(function ($row) {

		});
	}
	protected function getZjnameAttr($value, $data) {
		return isset($data['puserid']) ? $this->where('userid', $data['puserid'])->value('realname') : '未分配';
	}
	protected function getStoreNameAttr($value, $data) {
		return isset($data['dealerid']) ? $this->where('userid', $data['dealerid'])->value('realname') : '未分配';
	}
	protected function getRolenameAttr($value, $data) {
		if (!isset($data['roleid'])) {
			return false;
		}
		$authGroup = cache("AuthGroup");
		return $data['roleid'] ? $authGroup[$data['roleid']]['title'] : '未知';
	}
	protected function getVipenddateAttr($value, $data) {
		return isset($data['vipendtime']) && $data['vipendtime'] ? date('Y-m-d', $data['vipendtime']) : '未购买';
	}
	protected function getAlldataAttr($value, $data) {
		$authGroup = cache("AuthGroup");
		$status = [0 => '正常', 1 => '禁用', 99 => '待激活'];
		$data['rolename'] = $data['roleid'] ? $authGroup[$data['roleid']]['title'] : '未知';
		$data['addtime'] = $data['addtime'] ? date("Y-m-d H:i", $data['addtime']) : '未知';
		$data['lastlogintime'] = $data['lastlogintime'] ? date("Y-m-d H:i", $data['lastlogintime']) : '未登录';
		$data['statusname'] = $status[$data['status']];
		// $data['dealer'] = model('AdminUser')->get_dealer($data['userid'], $data['dealerid'], $data['roleid']);
		$data['dealer'] = $data['dealerid'] ? $this->where('userid', $data['dealerid'])->value('realname') : '--';
		$data['isvip'] = $data['vip'] ? '是' : '否';
		$data['province'] = isset($data['province_code']) && $data['province_code'] ? model('City')->where('code', $data['province_code'])->value('title') : '未设置';
		$data['city'] = isset($data['city_code']) && $data['city_code'] ? model('City')->where('code', $data['city_code'])->value('title') : '未设置';
		//
		if (!isset($data['roleid'])) {
			return false;
		}
		$authGroup = cache("AuthGroup");
		$data['rolename'] = $data['roleid'] ? $authGroup[$data['roleid']]['title'] : '未知';
		return $data;
	}
	protected function getProvinceAttr($value, $data) {
		return isset($data['province_code']) && $data['province_code'] ? model('City')->where('code', $data['province_code'])->value('title') : '未设置';
	}
	protected function getCityAttr($value, $data) {
		return isset($data['city_code']) && $data['city_code'] ? model('City')->where('code', $data['city_code'])->value('title') : '未设置';
	}
	protected function getLastlogintimeAttr($value) {
		return $value ? date("Y-m-d H:i", $value) : '未登录';
	}
	// protected function getAddtimeAttr($value, $data){
	// 	return $value ? date("Y-m-d H:i",$value) : '未知';
	// }
	protected function getFullnameAttr($value, $data) {
		return isset($data['fullname']) && $data['fullname'] ? $data['fullname'] : (isset($data['username']) && $data['username'] ? $data['username'] : '');
	}
	protected function getAvatarAttr($value, $data) {
		// $value = $value ? $value : '/upload/20171123/85fb39b735ea0559e3be7479e85e3225.png';
		$value = $value ? $value : '/public/static/images/logo.png';
		if (strpos($value, "http://") !== false) {
			return $value;
		} else {
			return $value ? rtrim(APP_URL, "/") . $value : '';
		}
	}
	protected function getStatusnameAttr($value, $data) {
		if (empty($data)) {
			return false;
		}
		$status = [0 => '正常', 1 => '禁用', 99 => '待激活'];
		return $status[$data['status']];
	}
	//所属经销商
	protected function getDealerAttr($value, $data) {
		return $this->get_dealer($data['userid'], $data['puserid'], $data['roleid']);
	}
	//上级
	protected function getPrealnameAttr($value, $data) {
		return $this->where('userid', $data['puserid'])->value('realname');
	}
	//社会身份
	protected function getIdentityNameAttr($value, $data) {
		return isset($data['identity']) ? config('IDENTITY.' . $data['identity']) : '未设置';
	}
	protected function setPasswordAttr($value) {
		return md5($value);
	}
	// protected function setStatusAttr($value, $data){
	// 	return $data['roleid'] == 9 ? 99 : 0;
	// }
	protected function setRegisterCodeAttr($value, $data) {
		if (isset($data['roleid']) && $data['roleid'] == 9) {
			return $this->create_code();
		}
		return '';
	}
	protected function setInitialAttr($value, $data) {
		$str = get_charter($data['realname']);
		return $str ? strtoupper(substr($str, 0, 1)) : '#';
	}
	protected function setAvatarAttr($value, $data) {
		return isset($data['avatar']) && $data['avatar'] ? $data['avatar'] : '/public/static/images/logo.png';
	}
	private function create_code() {
		$code = create_randomstr(8);
		$count = $this->where('register_code', $code)->count();
		if ($count) {
			return $this->create_code();
		}
		return $code;
	}
	public function save_data($data) {
		if (isset($data['fullname'])) {
			$this->validate("AdminUser.add_dealer");
		} elseif (isset($data['idcard'])) {
			$this->validate("AdminUser.add_subord");
		} else {
			$this->validate("AdminUser.add");
		}
		trace($data);
		$result = $this->save($data);
		if ($result !== false) {
			$pk = $this->getPk();
			$id = $this->$pk;
			return $id;
		}
		return false;
	}
	public function save_data_new($data) {
		$insert = [
			'username' => $data['phone'],
			'password' => $data['password'],
			'realname' => $data['realname'],
			'phone' => $data['phone'],
			'dealerid' => $data['dealerid'],
			'nickname' => isset($data['nickname']) ? $data['nickname'] : $data['username'],
			'roleid' => 9,
			'lastloginip' => request()->ip(),
			'lastlogintime' => time(),
			'signs' => 1,
		];
		$adminuser = $this->create($insert);
		return $this->where('userid', $adminuser->userid)->find();
	}
	public function forget_pwd($data) {
		// if ($data['userid']) {
		// 	$where['userid'] = $data['userid'];
		// } else {
		// 	$where['phone'] = $data['phone'];
		// }
		$where['phone'] = $data['phone'];
		$this->where($where)->setField('password', md5('12345'));
		return $this->where($where)->setField('password', md5($data['password']));
	}
	// public function get_data($data, $except = '', $field = '') {
	// 	$data = parent::get_data($data, 'password, paypassword');
	// 	return $data;
	// }
	public function update_data($data) {
		if (isset($data['fullname'])) {
			if ($data['password'] || $data['repassword']) {
				$this->validate('AdminUser.edit_dealer_pwd');
			} else {
				unset($data['password']);
				$this->validate('AdminUser.edit_dealer');
			}
		} elseif (isset($data['password']) || isset($data['repassword'])) {
			if ($data['password'] || $data['repassword']) {
				$this->validate('AdminUser.edit_pwd');
			} else {
				unset($data['password']);
				$this->validate('AdminUser.edit');
			}
		}
		trace($data);
		$result = $this->allowField(true)->isUpdate(true)->save($data);
		if ($result !== false) {
			$pk = $this->getPk();
			$id = $this->$pk;
			return $id;
		}
		return false;
	}
	public function login($username, $password) {
		$uinfo = $this->where("username='$username'")->find();
		$msg = '';
		$result = 0;
		if ($uinfo) {
			$pwd = md5($password);
			if ($uinfo['password'] == $pwd && !in_array($uinfo['roleid'], [5, 7, 8, 9])) {
				//记录登录时间
				$uid = $uinfo['userid'];
				$this->where("userid='$uid'")->update(['lastlogintime' => SYS_TIME]);
				$msg = '登录成功！';
				session("uinfo", $uinfo);
				session("islogin", 1);
				session("username", $username);
				session("realname", $uinfo['realname']);
				$result = 1;
			} else {
				$msg = '账号密码错误！';
			}
		} else {
			$msg = '用户名不存在！';
		}
		return [$result, $msg];
	}
	public function login_phone($phone, $password) {
		$iscount = $this->where("username|phone|email", $phone)->where("password", $password)->count();
		trace($this->getlastsql());
		trace($iscount);
		if ($iscount) {
			$userid = $this->where("username|phone|email", $phone)->where("password", $password)->value("userid");
			$this->where('userid', $userid)->setField("lastlogintime", SYS_TIME);
			return $userid;
		}
		return false;
	}
	public function list_subords($userid, $roleid, $puserid) {
		$list = [];
		if (in_array($roleid, [8, 10, 11])) {
			$dealerid = model('AdminUser')->where('userid', $userid)->value('dealerid');
			$where = [];
			if ($roleid == 8) {
				//2020年0316李国注销掉此行，因客户要求让总监查看到所有会员列表，不再限制是否上报了线索
				//$where = ['gouchetag' => '1'];
			} else if ($roleid == 10) {
				$where = ['xubaotag' => '1'];
			} else if ($roleid == 11) {
				$where = ['baoyangtag' => '1'];
			}
			$list = model('AdminUser')->where('dealerid', $dealerid)->where($where)->field('userid,username,fullname,phone,realname,email,roleid,avatar,initial,province_code,city_code,area_code')->order('initial asc,userid asc')->select();
		} else {
			$puserids = $this->get_all_childs($userid, $roleid, $puserid);
			$where['puserid'] = ['in', $puserids];
			$list = $this->where($where)->field('userid,username,fullname,phone,realname,email,roleid,avatar,initial,province_code,city_code,area_code')->order('initial asc,userid asc')->select();
		}
		$lists = [];
		foreach ($list as $v) {
			if (isset($lists[$v['initial']])) {
				$lists[$v['initial']]['list'][] = $v;
			} else {
				$lists[$v['initial']]['title'] = $v['initial'];
				$lists[$v['initial']]['list'][] = $v;
			}
		}
		return $lists;
	}
	public function get_userid($puserid, $roleid) {
		// trace($puserid);
		if (!$puserid) {
			return false;
		}
		$info = $this->where('userid', $puserid)->find();
		if ($info['roleid'] == $roleid) {
			return $puserid;
		}
		return $this->get_userid($info['puserid'], $roleid);
	}
	public function get_nickname($userid) {
		$info = model('AdminUser')->where('userid', $userid)->field('username, fullname, nickname, phone')->find();
		return $info['nickname'] ? $info['nickname'] : ($info['username'] ? $info['username'] : ($info['phone'] ? $info['phone'] : $info['fullname']));
	}
	//获取销售总监
	public function get_all_childs($userid, $roleid, $puserid, $keywords = '') {
		$where = [];
		if ($keywords) {
			$where['realname'] = ['like', "%$keywords%"];
		}
		switch ($roleid) {
		case 4:
			$list6 = $this->where('roleid', 6)->where('puserid', $userid)->order('userid desc')->select();
			$info6 = [];
			foreach ($list6 as $v) {
				$info6[] = $v['userid'];
			}

			$where['puserid'] = ['in', $info6];
			$where['roleid'] = 8;
			$list = $this->where($where)->order('userid desc')->select();
			$info8 = [];
			foreach ($list as $v) {
				$info8[] = $v['userid'];
			}
			return $info8;
			break;
		case 5:
			$list = $this->where('puserid', $puserid)->where('roleid', 6)->order('userid desc')->select();
			$info6 = [];
			foreach ($list as $v) {
				$info6[] = $v['userid'];
			}
			$where['puserid'] = ['in', $info6];
			$where['roleid'] = 8;
			$list = $this->where($where)->order('userid desc')->select();
			$info8 = [];
			foreach ($list as $v) {
				$info8[] = $v['userid'];
			}
			return $info8;
			break;
		case 6:
			$where['puserid'] = $userid;
			$where['roleid'] = 8;
			$list = $this->where($where)->order('userid desc')->select();
			$info8 = [];
			foreach ($list as $v) {
				$info8[] = $v['userid'];
			}
			return $info8;
			break;
		case 7:
			$where['puserid'] = $puserid;
			$where['roleid'] = 8;
			$list = $this->where($where)->order('userid desc')->select();
			$info8 = [];
			foreach ($list as $v) {
				$info8[] = $v['userid'];
			}
			return $info8;
			break;
		case 8:
			return [$userid];
			break;
		}
	}
	//所属经销商
	public function get_dealer($userid, $puserid = 0, $roleid = 0) {
		if ($roleid <= 6 && $roleid > 0) {
			return '无';
		}
		if ($puserid == 0) {
			$info = $this->where('userid', $userid)->field('userid, puserid, roleid, realname')->find();
			if ($info['roleid'] < 6) {
				return '无';
			} elseif ($info['roleid'] == 6) {
				return $info['realname'];
			} else {
				$userid = $info['userid'];
				$puserid = $info['puserid'];
				$roleid = $info['roleid'];
			}
		}
		if ($roleid == 9) {
			$pinfo = $this->where('userid', $puserid)->field('userid,roleid,puserid,realname')->find();
			if ($pinfo['roleid'] == 6) {
				return $pinfo['realname'];
			} else {
				$puserid = $pinfo['puserid'];
			}
		}
		return $this->where('userid', $puserid)->value('realname');
	}
	//获取该管理员下的所有用户id
	public function get_all_userids($userid, $roleid, $where = []) {
		$info = [];
		switch ($roleid) {
		case 4:
			$dealer_list = $this->where('puserid', $userid)->where('roleid', 6)->field('userid')->order('userid asc')->select();
			$dealer_info = [];
			foreach ($dealer_list as $v) {
				$dealer_info[] = $v['userid'];
			}
			$zongjian_list = $this->where('puserid', 'in', $dealer_info)->where('roleid', 8)->field('userid')->order('userid asc')->select();
			$zongjian_info = [];
			foreach ($zongjian_list as $v) {
				$zongjian_info[] = $v['userid'];
			}
			$puserids = array_merge($dealer_info, $zongjian_info);
			$puserids[] = $userid;
			if ($where) {
				$list = $this->where('puserid', 'in', $puserids)->where('roleid', 'neq', 6)->where($where)->field('userid')->order('userid asc')->select();
			} else {
				$list = $this->where('puserid', 'in', $puserids)->where('roleid', 'neq', 6)->field('userid')->order('userid asc')->select();
			}
			$info = [];
			foreach ($list as $v) {
				$info[] = $v['userid'];
			}
			$info[] = $userid;
			return $info;
			break;
		case 5: //userid  为上一级id
			$pinfo = $this->where('puserid', $userid)->field('userid, roleid, puserid')->find();
			$userid = $pinfo['userid'];
			$roleid = $pinfo['roleid'];
			$dealer_list = $this->where('puserid', $userid)->where('roleid', 6)->field('userid')->order('userid asc')->select();
			$dealer_info = [];
			foreach ($dealer_list as $v) {
				$dealer_info[] = $v['userid'];
			}
			$zongjian_list = $this->where('puserid', 'in', $dealer_info)->where('roleid', 8)->field('userid')->order('userid asc')->select();
			$zongjian_info = [];
			foreach ($zongjian_list as $v) {
				$zongjian_info[] = $v['userid'];
			}
			$puserids = array_merge($dealer_info, $zongjian_info);
			$puserids[] = $userid;
			if ($where) {
				$list = $this->where('puserid', 'in', $puserids)->where('roleid', 'neq', 6)->where($where)->field('userid')->order('userid asc')->select();
			} else {
				$list = $this->where('puserid', 'in', $puserids)->where('roleid', 'neq', 6)->field('userid')->order('userid asc')->select();
			}
			$info = [];
			foreach ($list as $v) {
				$info[] = $v['userid'];
			}
			return $info;
			break;
		case 6:
			$zongjian_list = $this->where('dealerid', $userid)->where('roleid', 'in', [8, 10, 11])->field('userid')->order('userid asc')->select();
			$puserids = [];
			foreach ($zongjian_list as $v) {
				$puserids[] = $v['userid'];
			}
			$puserids[] = $userid;
			if ($where) {
				$list = $this->where('dealerid', 'in', $puserids)->where($where)->field('userid')->order('userid asc')->select();
			} else {
				$list = $this->where('dealerid', 'in', $puserids)->field('userid')->order('userid asc')->select();
			}
			$info = [];
			foreach ($list as $v) {
				$info[] = $v['userid'];
			}
			$info[] = $userid;
			return $info;
			break;
		case 7: //userid  为上一级id
			$pinfo = $this->where('puserid', $userid)->field('userid, roleid, puserid')->find();
			$userid = $pinfo['userid'];
			$roleid = $pinfo['roleid'];
			$zongjian_list = $this->where('puserid', $userid)->where('roleid', 8)->field('userid')->order('userid asc')->select();
			$puserids = [];
			foreach ($zongjian_list as $v) {
				$puserids[] = $v['userid'];
			}
			$puserids[] = $userid;
			if ($where) {
				$list = $this->where('puserid', 'in', $puserids)->where($where)->field('userid')->order('userid asc')->select();
			} else {
				$list = $this->where('puserid', 'in', $puserids)->field('userid')->order('userid asc')->select();
			}
			$info = [];
			foreach ($list as $v) {
				$info[] = $v['userid'];
			}
			return $info;
			break;
		case 8:
			if ($where) {
				$list = $this->where('puserid', $userid)->where($where)->field('userid')->order('userid asc')->select();
			} else {
				$list = $this->where('puserid', $userid)->field('userid')->order('userid asc')->select();
			}
			$info = [];
			foreach ($list as $v) {
				$info[] = $v['userid'];
			}
			$info[] = $userid;
			return $info;
			break;
		}
	}
	//获取该管理员下的所有经销商id
	public function get_all_dealerids($userid, $roleid) {
		$where['roleid'] = 6;
		if ($roleid != 1) {
			$where['puserid'] = $userid;
		}
		$list = $this->where($where)->field('userid')->order('userid asc')->select();
		$info = [];
		foreach ($list as $v) {
			$info[] = $v['userid'];
		}
		return $info;
	}
}